﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Xsl;
using System.Web;

namespace Landscape
{
    class Template
    {
        public XmlDocument TemplateDom;
        public object TemplateCompiledTransform;
        public string TemplatePath;
        public List<string> DependenciesPaths = new List<string>();
        public OutputMethods OutputMethod = OutputMethods.Xml;

        public Template(string xmlTemplatePath)
        {
            TemplateDom = new XmlDocument();
            TemplateDom.Load(xmlTemplatePath);

            TemplatePath = xmlTemplatePath;
     
            // resolve smart include and imports and add them to dependencies along with template's path
            // so if one of these file changes, the whole cache is regenerated
            DependenciesPaths.Add(TemplatePath);
            ProcessDependencies(TemplateDom.GetElementsByTagName("include", Context.xslNamespace));
            ProcessDependencies(TemplateDom.GetElementsByTagName("import", Context.xslNamespace));
        }

        protected XslCompiledTransform CreateCompiledTransform(XmlDocument stylesheet) {
            XslCompiledTransform xsltCompiled = new XslCompiledTransform();

            xsltCompiled.Load(stylesheet, new XsltSettings(true, true), new TemplateXmlUrlResolver(Context.Library.includePaths));

            return xsltCompiled;
        }

        private void ProcessDependencies(XmlNodeList depNodes) {
            if (depNodes != null && depNodes.Count > 0) {
                foreach (XmlNode depNode in depNodes) { 
                    XmlNode depHrefNode = depNode.Attributes.GetNamedItem("href");
                    if (depHrefNode != null && !string.IsNullOrEmpty(depHrefNode.Value)) {
                        Uri depUri = new TemplateXmlUrlResolver(Context.Library.includePaths).ResolveUri(new Uri(TemplatePath), depHrefNode.Value);

                        // add dependency and resolve href into template
                        if (depUri != null) {
                            DependenciesPaths.Add(depUri.AbsolutePath);
                            depHrefNode.Value = depUri.AbsolutePath;
                        }
                    }
                }
            }
        }

        // TODO: find a smart way to implement the static GetTemplate method here returning the desired object type
        // public static object GetTemplate(string templatePath, System.Type returnType);
    }
}
